<template>
  <div class="gl_contentBox gl_heightFull">

    <el-tabs v-model="activeTab" class="gl_tabs" type="card">
      <el-tab-pane label="基础信息" name="0">
        <personal-info ref="refPersonalInfo" :photograph="true" :is-default-check="flag" :user-data="personalinfo" />
      </el-tab-pane>
      <el-tab-pane label="会员信息" name="1">
        <!-- 中跆协会员 -->
        <modMemberInfo ref="refModMemberInfo" :dict="dictRoot.dict" :user-data="personalinfo" form-size="mini" :hide-title="true" :hide-style="true" />
      </el-tab-pane>
      <el-tab-pane label="段位信息" name="2">
        <!-- 中跆协级位段位 -->
        <modTkwChiDan ref="refModTkwChiDan" class="gl_mb_20" :dict="dictRoot" :user-data="personalinfo" form-size="mini" :hide-style="true" />
        <!-- 国际台协段位 -->
        <modTkwIntDan ref="refModTkwIntDan" :dict="dictRoot" :user-data="personalinfo" form-size="mini" :hide-style="true" />
      </el-tab-pane>
    </el-tabs>
    <div>
      <span slot="footer" class="difooter">
        <!-- 取消按钮 -->
        <!-- <el-button size="mini">{{ $t('button.cancel') }}</el-button> -->
        <!-- 编辑的保存按钮 -->
        <!-- <el-button size="mini" type="primary" :loading="addfalse" @click="submit">{{ $t('button.submit') }}</el-button> -->
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="close">返回</el-button>
          <el-button size="mini" type="primary" :loading="submitLoading" @click="submit">{{ $t('button.submit') }}</el-button>
        </div>
      </span>
    </div>
  </div>
</template>

<script>
import { CopyData } from '@/lib';
import { mapState, mapActions } from 'vuex';
import {
  api_GET_EventsManagementRegisterId
} from '@/extend/api/gameswaggerApi/app';
import {
  SiSTKWEventsManagementCreateRegisterInput } from '@/lib/form/game/swaggerForm';
import { api_POST_ClubStudentRegisterStudent, api_PUT_ClubStudentRegisterStudentRegisterId } from '@/extend/api/hallswaggerApi/app.js';
import PersonalInfo from '@/components/PersonalInfo';
import modMemberInfo from '@/views/home/train/components/modMemberInfo.vue';
import modTkwChiDan from '@/views/home/train/components/modTkwChiDan.vue';
import modTkwIntDan from '@/views/home/train/components/modTkwIntDan.vue';
export default {
  components: {
    PersonalInfo,
    modMemberInfo,
    modTkwChiDan,
    modTkwIntDan
  },
  props: {
    father: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      flag: false,
      rid: '',
      submitLoading: false,
      dialogVisible: false,
      addfalse: false,
      activeTab: 0,
      personalinfo: new SiSTKWEventsManagementCreateRegisterInput(),
      createRegisterInput1: new SiSTKWEventsManagementCreateRegisterInput(),
      formData: {
        imageUrl: ''
      }
    };
  },
  computed: {
    ...mapState({
      dictRoot: state => state.dict,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      currentUserType: state => state.user.currentUserType,
      tags: state => state.user.tags
    })
  },
  created() {
    this.getDictByType(['district']);
    this.getDict();
    if (this.$route.query.rid) {
      this.$parent.tabdis = false;
      this.getStudent();
    } else {
      const a = {};
      a.name = JSON.parse(this.$route.query.role).name;
      a.idCardTypeCode = JSON.parse(this.$route.query.role).idCardTypeCode;
      a.idCardNumber = JSON.parse(this.$route.query.role).idCardNumber;

      this.personalinfo.name = JSON.parse(JSON.stringify(a)).name;
      this.personalinfo.idCardTypeCode = JSON.parse(JSON.stringify(a)).idCardTypeCode;
      this.personalinfo.idCardNumber = JSON.parse(JSON.stringify(a)).idCardNumber;
      this.$nextTick((res) => {
        this.$refs.refPersonalInfo.computGenderAndBirth();
      });
      CopyData(a, this.personalinfo);
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    submit() {
      this.submitLoading = true;
      this.$refs.refPersonalInfo.getInsideUserData().then(res => {
        this.createRegisterInput1 = JSON.parse(JSON.stringify(res));
        this.createRegisterInput1.isCurrentUser = true;
        this.createRegisterInput1.joinCurrentDelegation = false;
        this.createRegisterInput1.registerTypeCode = 'I';
        this.getFormsData();
      }, error => {
        this.submitLoading = false;
        this.activeTab = '0';
        this.$message({ type: 'error', message: (error.error && error.error.message) });
      });
    },
    getStudent() {
      return new Promise((resolve, reject) => {
        this.personInfoLoading = true;
        api_GET_EventsManagementRegisterId(
          this.$route.query.rid || this.rid
        ).then(res => {
          if (res.idCardTypeCode === 'IdCard') {
            this.flag = true;
          }
          this.personalinfo = JSON.parse(JSON.stringify(res));
          this.personInfoLoading = false;
          this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
          resolve(res);
          this.rid = '';
        }, error => {
          this.personInfoLoading = false;
          this.$message({ type: 'error', message: '获取个人信息失败！' + (error.error && error.error.message || '') });
          reject(error);
        });
      });
    },
    // 将数据合并到VO
    mergeFormDataToVO (list) {
      const _this = this;
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        CopyData(item, _this.createRegisterInput1);
      }
    },
    // 获取各个表单数据
    getFormsData () {
      const _all = [
        this.$refs['refModMemberInfo'].getInsideUserData(),
        this.$refs['refModTkwChiDan'].getInsideUserData(),
        this.$refs['refModTkwIntDan'].getInsideUserData()
      ];
      Promise.all(_all).then(res => {
        this.mergeFormDataToVO(res);
        if (this.$route.query.rid) {
          this.updateMemberInfo();
        } else {
          this.addMemberInfo();
        }
      }
      )
        .catch(
          error => {
            console.log('error: ', error);
            this.$message({
              message: `请先完善必填信息`,
              type: 'warning',
              showClose: true
            });
            this.submitLoading = false;
            if (error.component === 'memberInfo') {
              this.activeTab = '1';
            }
            if (error.component === 'tkwIntDan' || error.component === 'tkwChiDan') {
              this.activeTab = '2';
            }
          }
        );
    },
    addMemberInfo() {
      // 将空字符串转为Null, 部分后端类型不支持null. 所以移除为空字段
      for (const k in this.createRegisterInput1) {
        this.submitLoading = true;
        const ktem = this.createRegisterInput1[k];
        if (ktem === '' || ktem === null) {
          delete this.createRegisterInput1[k];
        }
      }
      // 将空字符串转为Null, 部分后端类型不支持null. 所以移除为空字段
      for (const k in this.createRegisterInput1) {
        const ktem = this.createRegisterInput1[k];
        if (ktem === '' || ktem === null) {
          delete this.createRegisterInput1[k];
        }
      }
      api_POST_ClubStudentRegisterStudent(this.createRegisterInput1).then((res) => {
        this.submitLoading = false;
        this.dialogVisible = false;
        this.rid = res.registerId;
        this.$router.push({ query: { 'id': res.id, 'rid': res.registerId }});
        this.getStudent();
        this.$message({ type: 'success', message: '添加成功' });
        this.$emit('listenToChildEvent', false);
      }, error => {
        this.$message({ type: 'error', message: (error.error && error.error.message) });
        this.submitLoading = false;
        this.dialogVisible = false;
      });
    },
    updateMemberInfo() {
      this.submitLoading = true;
      console.log(this.createRegisterInput1);
      api_PUT_ClubStudentRegisterStudentRegisterId(this.$route.query.rid, this.createRegisterInput1).then(() => {
        this.submitLoading = false;
        this.dialogVisible = false;
        this.getStudent();
        this.$message({ type: 'success', message: '修改成功' });
        // this.$router.push({ name: 'StudentList' });
      }, error => {
        this.$message({ type: 'error', message: (error.error && error.error.message) });
        this.submitLoading = false;
      });
    },
    close() {
      this.$router.push({ name: 'StudentList' });
    },
    goback() {
      this.$router.push({ name: 'StudentList' });
    }

  }
};
</script>

<style lang="scss" scoped>
.difooter {
  display: inline-block;
  margin-top: 20px;
  margin-left: 50%;
  transform: translateX(-50%);
}
</style>
